import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { RouteItem, filterRoutesByPermission } from '../config/routes';
import { api } from '../mock/dynamicRoutes';
import {
  DashboardOutlined,
  UserOutlined,
  SettingOutlined,
  ShoppingOutlined,
  OrderedListOutlined,
} from '@ant-design/icons';

interface RouterContextType {
  routes: RouteItem[];
  menuItems: any[];
  loading: boolean;
  refreshRoutes: () => Promise<void>;
}

const RouterContext = createContext<RouterContextType | undefined>(undefined);

export const useRouter = () => {
  const context = useContext(RouterContext);
  if (context === undefined) {
    throw new Error('useRouter must be used within a RouterProvider');
  }
  return context;
};

interface RouterProviderProps {
  children: ReactNode;
}

// 组件映射
const componentMap: { [key: string]: React.ComponentType } = {
  'Dashboard': React.lazy(() => import('../pages/Dashboard')),
  'UserManagement': React.lazy(() => import('../pages/UserManagement')),
  'UserProfile': React.lazy(() => import('../pages/UserProfile')),
  'SystemSettings': React.lazy(() => import('../pages/SystemSettings')),
  'RoleManagement': React.lazy(() => import('../pages/RoleManagement')),
  'MenuManagement': React.lazy(() => import('../pages/MenuManagement')),
  'ProductList': React.lazy(() => import('../pages/ProductList')),
  'ProductCategories': React.lazy(() => import('../pages/ProductCategories')),
  'OrderList': React.lazy(() => import('../pages/OrderList')),
  'OrderDetail': React.lazy(() => import('../pages/OrderDetail')),
};

// 图标映射
const iconMap: { [key: string]: React.ComponentType } = {
  'DashboardOutlined': DashboardOutlined,
  'UserOutlined': UserOutlined,
  'SettingOutlined': SettingOutlined,
  'ShoppingOutlined': ShoppingOutlined,
  'OrderedListOutlined': OrderedListOutlined,
};

// 转换路由数据
const transformRoutes = (routes: RouteItem[]): RouteItem[] => {
  return routes.map(route => ({
    ...route,
    icon: route.icon && typeof route.icon === 'string' ? iconMap[route.icon] : route.icon,
    component: route.component && typeof route.component === 'string' ? componentMap[route.component] : route.component,
    children: route.children ? transformRoutes(route.children) : undefined
  }));
};

// 生成菜单项的辅助函数
const generateMenuItems = (routes: RouteItem[]): any[] => {
  return routes
    .filter(route => !route.hideInMenu)
    .map(route => {
      const menuItem: any = {
        key: route.path,
        label: route.label,
      };

      if (route.icon) {
        menuItem.icon = React.createElement(route.icon);
      }

      if (route.children && route.children.some(child => !child.hideInMenu)) {
        menuItem.children = generateMenuItems(route.children);
      }

      return menuItem;
    });
};

export const RouterProvider: React.FC<RouterProviderProps> = ({ children }) => {
  const [routes, setRoutes] = useState<RouteItem[]>([]);
  const [menuItems, setMenuItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const loadRoutes = async () => {
    setLoading(true);
    try {
      // 并行获取路由和权限
      const [routesData, permissions] = await Promise.all([
        api.getRoutes(),
        api.getUserPermissions()
      ]);

      // 转换路由数据
      const transformedRoutes = transformRoutes(routesData);
      
      // 根据权限过滤路由
      const filteredRoutes = filterRoutesByPermission(transformedRoutes, permissions);
      
      setRoutes(filteredRoutes);
      
      // 生成菜单项
      const menuItems = generateMenuItems(filteredRoutes);
      setMenuItems(menuItems);
      
    } catch (error) {
      console.error('加载路由失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadRoutes();
  }, []);

  const value: RouterContextType = {
    routes,
    menuItems,
    loading,
    refreshRoutes: loadRoutes
  };

  return (
    <RouterContext.Provider value={value}>
      {children}
    </RouterContext.Provider>
  );
};

// 导出类型
export type { RouterContextType };